package org.bugjail.integration.mantis.dataaccess.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnectionManager {
	private final String DRIVER = "driver";
	private final String URL = "url";
	private final String USER = "user";
	private final String PASSWORD = "password";
	private final String PROPERTIES_FILE = "/org/bugjail/integration/mantis/dataaccess/database/connection.properties";

	private Properties properties;
	private static ConnectionManager instance;

	private ConnectionManager() {
		try {
			properties = new Properties();
			properties.load(getClass().getResourceAsStream(PROPERTIES_FILE));
		} catch (Exception e) {
			throw new ConnectionException(e.getMessage());
		}
	}

	protected static synchronized ConnectionManager getInstance() {
		if (instance == null) {
			instance = new ConnectionManager();
		}
		return instance;
	}

	protected Connection connect() {
		try {
			Connection connection = null;
			String driver = properties.getProperty(DRIVER);
			String url = properties.getProperty(URL);
			String usuario = properties.getProperty(USER);
			String senha = properties.getProperty(PASSWORD);
			Class.forName(driver);
			connection = DriverManager.getConnection(url, usuario, senha);
			connection.setAutoCommit(false);
			return connection;
		} catch (Exception e) {
			throw new ConnectionException(e.getMessage());
		}
	}

	protected void close(Connection connection) {
		try {
			connection.close();
		} catch (Exception e) {
			throw new ConnectionException(e.getMessage());
		}
	}
}
